from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from mainsite import models, forms
from django.core.mail import send_mail
from django.template.loader import get_template
from django.contrib import auth
from django.contrib.auth.models import User
from django.template import RequestContext
from django.contrib.messages import add_message, get_messages, SUCCESS, INFO, WARNING
from datetime import datetime
from django.db.models import Q
from mainsite.models import Post, comments, collect
from django.db.models import F
import time
import re
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from PIL import Image
from datetime import datetime
import uuid, os


# 文章投稿板块
def write(request):
    username = "投稿中心"
    moods = models.Mood.objects.all()
    show_message = '为了提高投稿审核通过率，要求数据可靠、逻辑严密、文字精炼、填写完整...'
    try:
        if request.method == 'POST':
            user_title = request.POST['user_title']
            user_people = request.POST['user_people']
            user_keyword = request.POST['user_keyword']
            user_picture = request.POST['user_picture']
            user_source = request.POST['user_source']
            user_body = request.POST['user_body']

            if username != None:
                try:
                    global post_new
                    post_new=models.Post.objects.create(title=user_title,body=user_body,people=user_people,keyword=user_keyword,picture=user_picture,source=user_source)
                    print(post_new)
                except Exception as e:
                    print(e)
                time.sleep(5)
                post_new.save()
                show_message = '投稿成功，请等待审核，感谢您的参与！'
    except Exception as e:
        print('投稿失败:',e)
        show_message = '投稿失败！请检查信息是否填写完整。'

    return render(request, "write.html", locals())


# 意见反馈板块
def contact(request):
    if request.user.is_authenticated:
        username = request.user.username

    userinfo = request.user
    if request.method == 'POST':
        form = forms.ContactForm(request.POST)
        if form.is_valid():
            message = "感谢您的来信，我们会尽速处理您的宝贵意见。"
            user_name = form.cleaned_data['user_name']
            user_product = form.cleaned_data['user_product']
            user_marks = form.cleaned_data['user_marks']
            user_email = form.cleaned_data['user_email']
            user_message = form.cleaned_data['user_message']

            mail_title = u'''来自知识与你分享{}的建议信'''.format(user_name)
            mail_body = u'''
客户姓名: {}  
反馈产品: {} 
网站评分: {} 
电子邮箱: {} 
网站建议内容如下: 
❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀
{}
❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀'''.format(user_name, user_product, user_marks, user_email, user_message)

            send_mail(mail_title, mail_body, '3300838154@qq.com',
                      ['3300838154@qq.com'], fail_silently=False)

        else:
            message = "请检查您输入的信息是否正确!"
    else:
        form = forms.ContactForm()

    return render(request, "contact.html", locals())


# 个人首页板块
def home(request):
    if request.user.is_authenticated:
        username = request.user.username
        userinfo = request.user
        userprofileinfo = models.Profile.objects.get(user=userinfo)
    else:
        username = ""
    userinfo = request.user
    now = datetime.now()
    hour = now.timetuple().tm_hour
    post = Post.objects.all().order_by('-likes').values('id', 'people', 'picture', 'title', 'likes', 'pub_date',
                                                        'keyword', 'body', 'source')
    post = post[0]
    new = Post.objects.all().values('id', 'people', 'picture', 'title', 'likes', 'pub_date', 'keyword', 'body',
                                    'source')
    new = new[0]
    comment = models.comments.objects.filter(post_id=post['id'])
    comment = len(comment)
    newcom = models.comments.objects.filter(post_id=new['id'])
    newcom = len(newcom)
    template = get_template('home.html')
    html = template.render(locals())
    return HttpResponse(html)


# 删除评论板块
def delcom(request, pid=None, s=None):
    if pid:
        try:
            post = models.comments.objects.get(id=pid)
        except:
            post = None
        if post:
            time.sleep(1.2)
            post.delete()
    return redirect('/post/' + s)


# 文章搜索板块
def search(request, s):
    if request.user.is_authenticated:
        username = request.user.username

    userinfo = request.user
    '''posts = Post.objects.filter(
        Q(keyword__contains=s) | Q(body__contains=s) | Q(pub_date__contains=s) | Q(people__contains=s) | Q(
            source__contains=s) | Q(title__contains=s))'''
    allposts = Post.objects.filter(
        Q(keyword__contains=s) | Q(body__contains=s) | Q(pub_date__contains=s) | Q(people__contains=s) | Q(
            source__contains=s) | Q(title__contains=s))
    postPaginator = Paginator(allposts, 4, 1)
    page = request.GET.get('page')
    try:
        posts = postPaginator.page(page)
    except PageNotAnInteger:
        posts = postPaginator.page(1)
    except EmptyPage:
        posts = postPaginator(postPaginator.num_pages)
    template = get_template('index.html')
    messages = get_messages(request)
    html = template.render(locals())
    return HttpResponse(html)


# 热榜文章板块
def hotnews(request):
    if request.user.is_authenticated:
        username = request.user.username

    userinfo = request.user
    template = get_template('index.html')
    allposts = Post.objects.all().order_by('-likes')
    postPaginator = Paginator(allposts, 4, 1)
    page = request.GET.get('page')
    try:
        posts = postPaginator.page(page)
    except PageNotAnInteger:
        posts = postPaginator.page(1)
    except EmptyPage:
        posts = postPaginator(postPaginator.num_pages)
    messages = get_messages(request)
    html = template.render(locals())
    return HttpResponse(html)


# 文章分类板块
def news(request, s):
    if request.user.is_authenticated:
        username = request.user.username

    userinfo = request.user
    #posts = Post.objects.filter(keyword=s)
    allposts = Post.objects.filter(keyword=s)
    postPaginator = Paginator(allposts, 4, 0)
    page = request.GET.get('page')
    try:
        posts = postPaginator.page(page)
    except PageNotAnInteger:
        posts = postPaginator.page(1)
    except EmptyPage:
        posts = postPaginator(postPaginator.num_pages)
    template = get_template('index.html')
    now = datetime.now()
    messages = get_messages(request)
    html = template.render(locals())
    return HttpResponse(html)


# 显示单篇文章板块
def showpost(request, s):
    if request.user.is_authenticated:
        username = request.user.username

    userinfo = request.user
    a = Post.objects.first()
    a = str(a.id)
    while s!="0":
        # if s == "13":
        #     s=a
        # if int(s) == int(a)-1:
        #     s = "12"
        try:
            post = Post.objects.get(id=s)
            comment = models.comments.objects.filter(post_id=s).order_by('-pub_time')
            collect = models.collect.objects.filter(nickname=username)
            collect = list(collect)
            collect = [int(s) for s in re.findall(r'\d+', str(collect))]

            if request.method == 'POST':
                com_post = request.POST['comment']
                if com_post != "":
                    comment_post = models.comments.objects.create(nickname=username, post_id=s, message=com_post)
                    comment_post.save()

            if post != None:
                return render(request, "post.html", locals())
        except:
            s=str(int(s)-1)
    return redirect('/list/')


# 收藏列表板块
def collect(request):
    if request.user.is_authenticated:
        username = request.user.username

    userinfo = request.user
    collect = models.collect.objects.filter(nickname=username)
    '''
    posts = []
    for coll in collect:
        post = Post.objects.get(id=coll.post_id)
        posts.append(post)
'''
    allposts = []
    for coll in collect:
        post = Post.objects.get(id=coll.post_id)
        allposts.append(post)
    postPaginator = Paginator(allposts, 4, 1)
    page = request.GET.get('page')
    try:
        posts = postPaginator.page(page)
    except PageNotAnInteger:
        posts = postPaginator.page(1)
    except EmptyPage:
        posts = postPaginator(postPaginator.num_pages)


    template = get_template('index.html')
    now = datetime.now()
    messages = get_messages(request)
    html = template.render(locals())
    return HttpResponse(html)


# 添加收藏板块
def add_collect(request, s):
    if request.user.is_authenticated:
        username = request.user.username

    coll = models.collect.objects.filter(post_id=s)
    if coll.exists():
        pass
    else:
        coll = models.collect.objects.create(nickname=username, post_id=s)
        time.sleep(1.2)
        coll.save()
    return redirect('/post/' + s)


# 删除收藏
def del_collect(request, pid=None):
    if pid:
        try:
            post = models.collect.objects.get(post_id=pid)
        except:
            post = None
        if post:
            time.sleep(1.2)
            post.delete()
    return redirect('/post/' + pid)


# 点赞板块
def updatevote(request):
    pslug = request.GET['postslug']
    try:
        p = Post.objects.get(id=pslug)
        p.likes = p.likes + 1
        p.save()
    except:
        pass
    return HttpResponse(p.likes)


# 新闻主页板块
def index(request):
    if request.user.is_authenticated:
        username = request.user.username

    userinfo = request.user
    template = get_template('index.html')
    allposts = Post.objects.all().order_by('-pub_date')
    postPaginator = Paginator(allposts, 4, 0)
    page = request.GET.get('page')
    try:
        posts = postPaginator.page(page)
    except PageNotAnInteger:
        posts = postPaginator.page(1)
    except EmptyPage:
        posts = postPaginator(postPaginator.num_pages)
    now = datetime.now()
    messages = get_messages(request)
    html = template.render(locals())
    return HttpResponse(html)


# 登陆板块
def login(request):
    if request.method == 'POST':
        login_name = request.POST['username'].strip()
        login_password = request.POST['password']
        try:
            user = auth.authenticate(username=login_name, password=login_password)
            if user != None:
                if user.is_active:
                    auth.login(request, user)
                    # 登陆成功
                    username = request.user.username
                    if username == "RuiXin":
                        return redirect("/")
                    else:
                        return redirect("/")
                else:
                    add_message(request, WARNING, '账号未启用')
            else:
                add_message(request, WARNING, '亲，用户名或密码错误哟ヾ(•ω•`)o')
        except:
            add_message(request, WARNING, '亲，用户名或密码错误哟ヾ(•ω•`)o')

    return render(request, "login.html", locals())


# 注销板块
def logout(request):
    auth.logout(request)
    return redirect("/")


# 头像板块
def cropImage(imgfile):
    # 随机生成新的图片名，自定义路径
    ext = imgfile.name.split('.')[-1]
    file_name = '{}.{}'.format(uuid.uuid4().hex, ext)
    file_pathname = os.path.join("uploadfiles", file_name)
    # 获取图片操作对象
    img = Image.open(imgfile)
    # 相对根目录路径
    filePath = os.path.join("static", "uploadfiles", file_name)
    img.save(filePath)  # 将图片按filePath标识的路径保存在服务器上

    return file_pathname


# 注册板块
def register(request):
    if request.method == 'POST':
        newUsername = request.POST.get('username')
        password = request.POST.get('password')
        email = request.POST.get('email')
        male = request.POST.get('sex')
        if User.objects.filter(username=newUsername):
            add_message(request, WARNING, '该用户已存在')
        else:
            new_user = User.objects.create_user(username=newUsername, password=password, email=email)
            new_user.save()
            new_userprofile = models.Profile.objects.create(user=new_user, male=male)
            img = request.FILES.get('avatar')
            if img != None:
                cropped_avatar = cropImage(img)
                new_userprofile.avatar = cropped_avatar
                new_userprofile.save()
            add_message(request, SUCCESS, '注册成功了哟')

            return redirect("/login/")

    return render(request, "register.html", locals())


# 个人名片板块
def userinfo(request):
    if request.user.is_authenticated:
        username = request.user.username
    userinfo = request.user
    userprofileinfo = models.Profile.objects.get(user=userinfo)

    template = get_template('userinfo.html')
    html = template.render(locals())
    return HttpResponse(html)


# 修改密码板块
def modifypwd(request):
    if request.method == 'POST':
        oldpwd = request.POST['oldpassword']
        newpwd = request.POST['newpassword']
        if request.user.check_password(oldpwd):
            request.user.set_password(newpwd)
            request.user.save()
            auth.logout(request)
            add_message(request, SUCCESS, '密码修改成功')
            return redirect("/login/")
        else:
            add_message(request, WARNING, '旧密码错误')

    return render(request, "modifypwd.html", locals())


# 检查用户名板块
def checkusername(request):
    newUsername = request.GET.get('username')
    if User.objects.filter(username=newUsername):
        return HttpResponse("1")
    else:
        return HttpResponse("0")


# 图片板块
def photo(request):
    if request.user.is_authenticated:
        username = request.user.username

    userinfo = request.user
    allposts = models.Post.objects.all()
    postPaginator = Paginator(allposts, 6, 0)
    page = request.GET.get('page')
    try:
        posts = postPaginator.page(page)
    except PageNotAnInteger:
        posts = postPaginator.page(1)
    except EmptyPage:
        posts = postPaginator(postPaginator.num_pages)
    template = get_template("photo.html")
    html = template.render(locals())
    return HttpResponse(html)


# 图片详情板块
def showphoto(request, s):
    if request.user.is_authenticated:
        username = request.user.username
    userinfo = request.user
    template = get_template('showphoto.html')
    a = Post.objects.first()
    a = str(a.id)
    while s != "0":
        if s == "13":
            s = a
        if int(s) == int(a) - 1:
            s = "12"
        try:
            post = Post.objects.get(id=s)
            if post != None:
                html = template.render(locals())
                return HttpResponse(html)

        except:
            return redirect('/photo/')


#查找好友
def findFri(request):
    if request.user.is_authenticated:
        username = request.user.username
    userinfo = request.user
    users=User.objects.all()

    return render(request,"FindFri.html",locals())

#好友评论
def friCom(request):
    if request.user.is_authenticated:
        username = request.user.username
    userinfo = request.user
    users=User.objects.all()

    return render(request,"friCom.html",locals())


def addFri(request):
    if request.user.is_authenticated:
        username = request.user.username
    userinfo = request.user
    users=User.objects.all()
    return render(request,"addFri.html",locals())
# 许愿池板块
'''
def wishing(request):
    if request.user.is_authenticated:
        username = request.user.username
    userinfo = request.user
    wishs = models.Wish.objects.filter(enabled=True).order_by('-pub_time')
    allwishs = models.Wish.objects.filter(enabled=True).order_by('-pub_time')
    wishPaginator = Paginator(allwishs, 6, 1)
    page = request.GET.get('page')
    try:
        wishs = wishPaginator.page(page)
    except PageNotAnInteger:
        wishs = wishPaginator.page(1)
    except EmptyPage:
        wishs = wishPaginator(wishPaginator.num_pages)
    moods = models.Mood.objects.all()
    if request.method=='POST':
        user_mood = request.POST.get('mood')
        user_post = request.POST.get('wish_post')
        mood = models.Mood.objects.get(status=user_mood)
        wish = models.Wish.objects.create(mood=mood, nickname=username, message=user_post)
        wish.save()
        return redirect('/wish/')


    return render(request,"wish.html",locals())'''
